//
//  PuzzleViewController.m
//  Days
//
//  Created by lanou3g on 16/1/8.
//  Copyright © 2016年 dss. All rights reserved.
//

#import "PuzzleViewController.h"

static int  kSideLength = 0;
@interface PuzzleViewController ()<imageDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@end

@implementation PuzzleViewController

//#define kSideLength  ([UIScreen mainScreen].bounds.size.width - 50) / 3

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([UIScreen mainScreen].bounds.size.width == 414 || [UIScreen mainScreen].bounds.size.width == 375 ) {
        kSideLength =  ([UIScreen mainScreen].bounds.size.width - 60) / 3;
    }else if ([UIScreen mainScreen].bounds.size.width == 320){
        kSideLength =  ([UIScreen mainScreen].bounds.size.width - 50) / 3;
    }
    
   //初始照片
   [self getImage:[UIImage imageNamed:@"Pom1"]];
    
    UIBarButtonItem *buttomChange = [[UIBarButtonItem alloc]initWithTitle:@"换图" style:UIBarButtonItemStylePlain target:self action:@selector(changeImage)];
    
    
    UIBarButtonItem *buttomCom =[[UIBarButtonItem alloc]initWithTitle:@"快速组图" style:UIBarButtonItemStylePlain  target:self action:@selector(combinationWithImage:)];
   
    self.navigationItem.rightBarButtonItems = @[buttomChange,buttomCom];
    
}

#pragma mark -- 照片
-(void)getImage:(UIImage *)img{
    
       //分割照片
     [self SeparateImage:img ByX:3 andY:3 cacheQuality:1];
    //设置缺少的那块frame
    self.tempimageView = [[UIImageView alloc]initWithFrame:CGRectMake(kSideLength * 2 + 10, 3 *kSideLength + 10, kSideLength, kSideLength)];
    self.tempimageView.tag = 100;
    [self.view addSubview:self.tempimageView];
    
    
    for (int i = 0; i < 3; i ++) {
        for (int j = 0; j < 3; j ++) {
            NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"hua_%d_%d.jpg",i,j]];
            UIImage *image = [UIImage imageWithContentsOfFile:filePath];
            
            
            self.imgView = [[ImageView alloc]initWithImage:image];
            
            self.imgView.tag = i * 2 + j;
            if (i == 1) {
                self.imgView.tag = i * 2 + j + 1;
            }
            if (i == 2) {
                self.imgView.tag = i * 2 + j + 2;
            }
//            if (i == 3) {
//                self.imgView.tag = i * 2 + j + 3;
//            }
            
            //设置代理
            self.imgView.delegate = self;
            self.imgView.frame = CGRectMake(kSideLength * i + 10, kSideLength * (j + 1) + 10, kSideLength, kSideLength);
            //添加到视图
            [self.view addSubview:self.imgView];
            
            
        }
    }
   
    ImageView *imag = (ImageView *)[self.view viewWithTag:self.imgView.tag];
    imag.hidden = YES;

    
    
}


#pragma mark -- 实现协议方法
-(void)movedectioon:(UIImageView *)imageView{
    
    CGFloat wid = imageView.frame.origin.x;
    CGFloat hig = imageView.frame.origin.y;
    
    if (self.tempimageView.frame.origin.x == wid + kSideLength && self.tempimageView.frame.origin.y == hig) {
        //右移
       
        [self rightchange:imageView];
        
    }
    if (self.tempimageView.frame.origin.x == wid - kSideLength && self.tempimageView.frame.origin.y == hig) {
       
        [self leftchange:imageView];
    }
    if (self.tempimageView.frame.origin.x == wid && self.tempimageView.frame.origin.y == hig + kSideLength) {
        
        [self downchange:imageView];
    }
    if (self.tempimageView.frame.origin.x == wid && self.tempimageView.frame.origin.y == hig - kSideLength) {
      
        [self upchange:imageView];
    }
}

#pragma mark -- 移动的方法
-(void)imageViewMove{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelay:0.3f];
    [UIView setAnimationDelegate:self];
}

#pragma mark -- 上移 
-(void)upchange:(UIImageView *)image{
    
    [self imageViewMove];
    image.frame = CGRectMake(image.frame.origin.x, image.frame.origin.y - kSideLength, kSideLength, kSideLength);
    self.tempimageView.frame = CGRectMake(image.frame.origin.x, image.frame.origin.y + kSideLength, kSideLength, kSideLength);
 
}
#pragma mark -- 下移
-(void)downchange:(UIImageView *)image{
    
    
    [self imageViewMove];
    
    image.frame = CGRectMake(image.frame.origin.x, image.frame.origin.y + kSideLength, kSideLength, kSideLength);
    self.tempimageView.frame = CGRectMake(image.frame.origin.x, image.frame.origin.y - kSideLength, kSideLength, kSideLength);
    
}

#pragma mark -- 左移
-(void)leftchange:(UIImageView *)image{
    [self imageViewMove];
    image.frame =CGRectMake(image.frame.origin.x - kSideLength,image.frame.origin.y, kSideLength, kSideLength);
    self.tempimageView.frame = CGRectMake(image.frame.origin.x +kSideLength, image.frame.origin.y, kSideLength , kSideLength);
}

#pragma mark -- 右移
-(void)rightchange:(UIImageView *)image{
    
    [self imageViewMove];
    image.frame = CGRectMake(image.frame.origin.x + kSideLength, image.frame.origin.y, kSideLength, kSideLength);
    self.tempimageView.frame = CGRectMake(image.frame.origin.x - kSideLength, image.frame.origin.y, kSideLength, kSideLength);
    
}



#pragma mark -- 分割照片
-(void)SeparateImage:(UIImage *)image ByX:(int)x andY:(int)y cacheQuality:(float)quality{
    
    if (x < 1) {
        
        return ;
    }else if(y < 1){
        
        return ;
    }
    
    if (![image isKindOfClass:[UIImage class]]) {
        
        return ;
    }
    
    float _xstep = image.size.width * 1.0 / y;
    float _ystep = image.size.height * 1.0 / x;
    
    for (int i = 0; i < x; i ++) {
        for (int j = 0; j < y; j ++) {
            CGRect rect = CGRectMake(_xstep * j, _ystep * i, _xstep, _ystep);
            
            CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
            
            UIImage *elementImage = [UIImage imageWithCGImage:imageRef];
            
            NSString *key = [NSString stringWithFormat:@"hua_%d_%d.jpg",i,j];
            
            if (quality<=0)
            {
                continue;
            }
            quality=(quality>1)?1:quality;
            
            NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            NSString*_imagePath=[path stringByAppendingPathComponent:key];
            NSData* _imageData=UIImageJPEGRepresentation(elementImage, quality);
            [_imageData writeToFile:_imagePath atomically:YES];
            
        }
        
           }
    
    
      
}

#pragma mark -- 快速组图
-(void)combinationWithImage:(UIImage *)image{
    //清除原来的
    [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    //分割照片
    [self SeparateImage:image ByX:3 andY:3 cacheQuality:1];
    
      
    //设置缺少的那块frame
    self.tempimageView = [[UIImageView alloc]initWithFrame:CGRectMake(kSideLength * 2 + 10, 3 *kSideLength + 10, kSideLength, kSideLength)];
    self.tempimageView.tag = 100;
    [self.view addSubview:self.tempimageView];
    
    
    for (int i = 0; i < 3; i ++) {
        for (int j = 0; j < 3; j ++) {
            NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"hua_%d_%d.jpg",j,i]];
            UIImage *image = [UIImage imageWithContentsOfFile:filePath];
            
            
            self.imgView = [[ImageView alloc]initWithImage:image];
            
            self.imgView.tag = i * 2 + j;
            if (i == 1) {
                self.imgView.tag = i * 2 + j + 1;
            }
            if (i == 2) {
                self.imgView.tag = i * 2 + j + 2;
            }
            //            if (i == 3) {
            //                self.imgView.tag = i * 2 + j + 3;
            //            }
            
            //设置代理
            self.imgView.delegate = self;
            self.imgView.frame = CGRectMake(kSideLength * i + 10, kSideLength * (j + 1) + 10, kSideLength, kSideLength);
            //添加到视图
            [self.view addSubview:self.imgView];
            
            
        }
    }
    
    ImageView *imag = (ImageView *)[self.view viewWithTag:self.imgView.tag];
    imag.hidden = YES;
    
    
    
}


#pragma mark -- 换图

-(void)changeImage{
    
    
      UIImagePickerController *imagePC = [[UIImagePickerController alloc]
                                        init];
    imagePC.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
    //设置代理
    imagePC.delegate  = self;
    
    imagePC.allowsEditing = YES;
    
    [self presentViewController:imagePC animated:YES completion:nil];
    
}


#pragma mark -- 调用相册协议方法
//选中方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSFileManager *manager = [[NSFileManager alloc]init];
    for (int i = 0; i < 3; i ++) {
        for (int j = 0; j < 3; j ++) {
            NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"hua_%d_%d.jpg",i,j]];
            [manager removeItemAtPath:filePath error:nil];
            
            
            
        }
    }
    
//清除原来的
    [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

    
    
    //从字典拿出照片
    UIImage *image = [info objectForKeyedSubscript:UIImagePickerControllerEditedImage];
    if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        //设置照片
        [self getImage:image];
        //快速组合图形方法
     //   [self combinationWithImage:image];
        
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
   
    
}

//取消
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
